import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { Dialog } from 'react-vant';

import Banner from '../Banner/index';
import Mode from '../Mode/index';
import Action from '../Action/index';

import { deviceId } from '@/utils/staticData';
import useStore from '@/store/index';
import {
  btnFitersText, runningTextConvert, workTimeMode
} from '@/utils/filters';

import './home.less';

export default function Home() {
  const Hejia = (window as any).Hejia;
  const location = useLocation();

  const { setInfo, info, stopLoop, setIsOperating, scheduleLoopStart, startLoop } = useStore();
  const { isOnline, mode, fault, state: status, booking } = info;

  useEffect(() => {
    setTimeout(() => {
      (window as any).bridge.callHandler(
        'setToolbarTitle',
        '小鸭智能破壁机XCX-886XY',
        null
      );
    }, 0);
  }, [location]);

  useEffect(() => {
    Hejia.ready(function () {
      startLoop();
    });
  }, []);

  const handleModeChange = (val: number) => {
    console.log('handleModeChange:', val);
    setInfo({ ...info, ...{ mode: val, Duration: workTimeMode(val) } });
  };

  const handleActionChange = (val: number, key: string) => {
    if (key === 'appointment') {
      setInfo({ ...info, ...{ booking: val } });
    }
  };

  const handleCancelCooking = () => {
    const cancelMessage = status === 1
      ? `设备${runningTextConvert(status)}中，确定要取消运行吗？`
      : `设备${runningTextConvert(status)}中，确定要取消${runningTextConvert(status)}吗？`;

    Dialog.confirm({
      message: cancelMessage,
      confirmButtonText: '确定',
      confirmButtonColor: 'var(--primary-color)',
      onCancel: scheduleLoopStart,
      onConfirm: () => {
        setInfo({
          ...info,
          mode: 0,
          booking: 0,
          state: 0
        });

        // 取消烹饪
        Hejia.setControlParam(
          {
            // deviceId,
            parameters: {
              param: [{ name: 'switch', content: 0 }]
            }
          },
          () => {
            scheduleLoopStart();
            console.log('success');
          },
          (msg: string, obj: any) => console.log(msg, obj)
        );
      }
    });
  };

  const handleStartCooking = () => {
    const newState = booking > 0 ? 2 : mode === 9 ? 3 : 1;
    setInfo({ ...info, state: newState });

    Hejia.setControlParam(
      {
        // deviceId,
        parameters: {
          param: [{ name: 'switch', content: 1 }]
        }
      },
      () => {
        scheduleLoopStart();
        console.log('success');
      },
      (msg: string, obj: any) => console.log(msg, obj)
    );
  };


  const onCooker = () => {
    stopLoop();
    setIsOperating(false);
    [1, 2, 3].includes(status) ? handleCancelCooking() : handleStartCooking();
  };

  const btnDisabled = !isOnline || mode === 0 || !!fault
  return (
    <div className="home">
      <div>
        <Banner />
        <Mode onModeChange={handleModeChange} />
        <Action onActionChange={handleActionChange} />

        <div className="home-mask-wapper">
          {btnDisabled && <div className="mask"></div>}
          <div className="footer">
            <div className="stop-btn" onClick={onCooker}>
              {btnFitersText(status, booking, mode)}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
